<script>
import $ from '@/common';
function billDataPath(bill_code) {
	return `/service/{app}/bill/data/${bill_code}/list`;
}
export default {
	props: {
		model: {},
		data: {},
		fetchMethod: {
			default: 'post',
		},
	},
	data() {
		return {
			//搜索路径
			searchPath: this.model && (this.model.bill_code ? billDataPath(this.model.bill_code) : this.model.path),
			//当前页
			pageOn: 1,
			//页长
			pageSize: 20,
			//总数量
			totalCount: 0,
			//总页码
			pageCount: 1,
			//搜索关键字
			searchKey: null,
			//是否分页
			tablePage: true,
			//原始数据
			tableData: [],
			//数据模型
			tableModel: [],
			//正在读取数据
			loading: false,
			//错误状态中
			onError: false,
			//创建时自动查询
			createdFetch: true,
			//数据追加模式
			appendData: false,
			//可以同时发送多个数据请求
			mulitQuery: false,
		};
	},
	created() {
		if (this.createdFetch) {
			this.fetch();
		}
	},
	methods: {
		query(key, ext) {
			this.filterKey = key;
			this.fetch(1, ext);
		},
		fetch(page = 1, ext) {
			//防止重复查询
			if (this.loading && !this.mulitQuery) {
				return new Promise((resolve, reject) => {
					reject();
				});
			}
			var url = this.searchPath;
			this.loading = true;
			var postData = {
				pageNo: page,
				pageSize: this.pageSize,
			};
			if (this.model && this.model.extPost) {
				$.setProp(postData, this.model.extPost);
			}
			if (url && this.filterKey && $.trim(this.filterKey).length) {
				url = $.setUrlQuery(url, { filter: this.filterKey });
				//postData.filter = $.trim(this.filterKey)
			}
			if (ext) {
				$.setProp(postData, ext);
			}
			//var searchPath = this.model.bill_code ? billDataPath(this.model.bill_code) : this.model.path
			if (!url) {
				return new Promise((resolve, reject) => {
					reject();
				});
			}
			return $.link(url, postData, {
				method: this.fetchMethod,
			})
				.then(res => {
					if (!this.fetchCheck()) {
						return;
					}
					if (res && res.status === 1 && res.data && res.data.data) {
						res = res.data;
					}
					res.data = this.dataProcess(res.data);
					if (res.pageNo > 1 && this.appendData) {
						res.data.forEach(row => {
							this.tableData.push(row);
						});
					} else {
						this.$set(this, 'tableData', res.data);
					}
					this.pageOn = res.pageNo || 1;
					this.pageSize = res.pageSize;
					this.pageCount = res.totalPageCount;
					this.totalCount = res.totalCount;
				})
				.finally(() => {
					this.loading = false;
				});
		},
		fetchNext(ext) {
			if (this.pageOn + 1 <= this.pageCount) {
				return this.fetch(this.pageOn + 1, ext);
			} else {
				return Promise.reject();
			}
		},
		fetchPrevious(ext) {
			if (this.pageOn - 1 >= 1) {
				this.fetch(this.pageOn - 1, ext);
			}
		},
		dataProcess(data) {
			return data;
		},
		searchData(key) {
			this.searchKey = key;
			this.fetch();
		},
		clearData() {
			this.searchKey = null;
			this.tableData = [];
			this.pageOn = 1;
		},
		//更新数据检测，返回false则可中断fetch更新数据
		fetchCheck() {
			return true;
		},
	},
};
</script>